package com.dianhun.cn.exhandler;

import com.dianhun.cn.ex.GlobalEx;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author cyt
 * @create 2020-08-26 11:28
 */
@Slf4j
@ControllerAdvice
public class GlobalExHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String error(Exception e) {
        e.printStackTrace();
        return "执行了异常";
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public String error(BindException e) {
        String msg = "";
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            allErrors.forEach(
                    p -> {
                        System.out.println(p);
                    }
            );
            FieldError objectError = (FieldError) allErrors.get(0);
            msg = objectError.getField();
            msg += "-> " + objectError.getDefaultMessage();

        }
        return msg;
    }

    @ExceptionHandler(GlobalEx.class)
    @ResponseBody
    public String error(GlobalEx e) {
        e.printStackTrace();
        return "执行的自定义异常";
    }
}
